<?php

class Silk_Zgb_Model_Observer
{
	public function saveProduct(Varien_Event_Observer $observer)
	{
		return;
		Mage::log('saveDealerId');
		$product = $observer->getProduct();
		$session = Mage::getSingleton('admin/session');
		$zgb = Mage::helper('zgb');
		$userId = $session->getUser()->getId();
		$roleId = $session->getUser()->getRoleId();
		$roles = Mage::helper('zgb')->getUserRoles();
		// Mage::log("roleid:{$roleId}");
		// if($roleId == 1) return;
		// 厂商保存商品时自动设置厂商ID
		// if($roleId == $zgb->getRoleId('manufacturer'))
		// {
		// 	if(!$product->getManufacturerId())
		// 	{
		// 		$model = Mage::getModel('zgb/manufacturer')->loadByAdminId($userId);
		// 		$product->setManufacturerId($model->getId());
		// 		Mage::log("manufacturer:".$model->getId());
		// 	}
		// }

		// 仓库领取商品
		// if($roleId == $zgb->getRoleId('warehouse'))
		// {
		// 	if(!$product->getOrigData('warehouse_id'))
		// 	{
		// 		$model = Mage::getModel('zgb/warehouse')->loadByAdminId($userId);
		// 		$product->setWarehouseId($model->getId());
		// 	}
		// }

		/*
			取消商品审核, 经销商只能修改库存,厂商暂不管理
			商品保存是如果商品没有设置正确的厂商,经销商,仓库则禁用商品.
		*/
		$data = $product->getData();
		if($data['store_id'] && $data['_edit_mode'])
		{
			$session = Mage::getSingleton('adminhtml/session');
			$disable = false;
			if(!$data['manufacturer_id']){
				$session->addError('厂商未设置');
				$disable = true;
			}
			if(!$data['dealer_id']){
				$session->addError('经销商未设置');
				$disable = true;
			}
			if(!$data['warehouse_id']){
				$session->addError('仓库未设置');
				$disable = true;
			}
			if($disable)
			{
				$session->addError('商品已禁用');
				$product->setStatus(2);
			}

			$orgData = $product->getOrigData();
			if($data['status']!=$orgData['status'])
			{
				$product->setStatusAt(Mage::getSingleton('core/date')->gmtDate());
			}
		}

		//Mage::log($data);
		$product->setVisibility(4);		



		//库存变更不修改商品状态
		/*
		if(in_array($roleId, $roles))
		{
			$data = $product->getData();
			$orgData = $product->getOrigData();
			$changed = false;
			//Mage::log($data);
			foreach($data as $key=>$val)
			{
				if(isset($orgData[$key]) && !is_object($orgData[$key]))
				{
					if($val && $val != $orgData[$key])
					{
						if($key=="media_gallery") continue;
						//Mage::log($key.":".$val);
						$changed = true;
					}
				}
			}

			// $stockItem = $product->getStockItem();
			// $stockData = $product->getStockData();

			// if(intval($stockData['qty'])!=intval($stockItem->getQty()))
			// {
			// 	$changed = true;
			// }

			//Mage::log($changed);
			if($changed)
			{
				$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);				
			}
		}
		*/
	}


	public function categoryInit(Varien_Event_Observer $observer)
	{
		$action = $observer->getControllerAction();
		//print_r($observer->getData());
		$categoryId = $action->getRequest()->getParam('id');
		$session = Mage::getSingleton('customer/session');
		$urlHelper = Mage::helper('core/url');
        if(!$session->isLoggedIn())
        {	
        	$url = Mage::getUrl('catalog/category/view',array('id'=>$categoryId));
            $action->getResponse()->setRedirect(Mage::getUrl('customer/account/login',array('referer'=>$urlHelper->getEncodedUrl($url))));
        }
	}

	public function checkRememberMe($observer)
	{
		$session = $observer->getEvent()->getCustomerSession();
		//Mage::log("OK");
		//Mage::log($session->isLoggedIn());
		$token = Mage::app()->getRequest()->getHeader('token');

		if(!$token) $token = Mage::app()->getRequest()->getParam('token');
		//Mage::log($token);
		if($token && !$session->isLoggedIn())
		{
			$model = Mage::getModel('mapi/token')->loadByToken($token);
			//Mage::log(Mage::app()->getWebsite()->getId());
			if($model->getId())
			{
				$customerId = $model->getCustomerId();
				$user = Mage::getModel('customer/customer')->setWebsiteId(Mage::app()->getWebsite()->getId())->load($customerId);
				if($user && $user->getId())
				{
					$observer->getEvent()->getCustomerSession()->loginById($user->getId());
				}
				
				// echo Mage::app()->getWebsite()->getId();
				// echo get_class($observer->getEvent()->getCustomerSession());
				// var_dump(Mage::getSingleton('customer/session')->isLoggedIn());
			}
			return;
		}
		

		if(!$session->isLoggedIn() && isset($_COOKIE['info_uid']) && isset($_COOKIE['info']))
		{
			//Mage::log("OK1");
			$user = Mage::getModel('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->load($_COOKIE['info_uid']);
			if ($user->getId())
			{
				//Mage::log("OK2");
				$salt = $user->getCreatedAtTimestamp();
				$pass = $user->getPasswordHash();
				$safe_pass = sha1(md5($pass).md5($salt));
				if($safe_pass == $_COOKIE['info'])
				{
					//Mage::log("OK3");
					$observer->getEvent()->getCustomerSession()->setCustomerAsLoggedIn($user);
					header("Location: ".Mage::helper('core/url')->getCurrentUrl());
					exit;
				}
			}
		}
		return;
	}

	public function initLanding($observer)
	{

		$action = $observer->getControllerAction();
		$template = Mage::getDesign()->getTheme('template');
		$allow = array('customer_account_login',
			'customer_account_landing',
			'customer_account_loginPost',
			'promotion_activity_view','promotion_exchange_view');
		$fullname = $action->getFullActionName();
		$names = explode('_',$fullname);

		if(count($names)>0 && $names[0]=="adminhtml") return;
		if(count($names)>0 && $names[0]=="customer") return;
		if(count($names)>0 && $names[0]=="zgb") return;
		if(count($names)>0 && $names[0]=="zgb_admin") return;
		if(count($names)>0 && $names[0]=="mapi") return;
		if(count($names)>0 && $names[0]=="amapi") return;
		if(count($names)>0 && $names[0]=="complex") return;
		if(count($names)>0 && $names[0]=="sales") return;
		if(count($names)>0 && $names[0]=="wishlist") return;
		if(count($names)>0 && $names[0]=="contacts") return;
		if(count($names)>0 && $names[0]=="promotion") return;
		if(count($names)>0 && $names[0]=="pms") return;
		if(count($names)>0 && $names[0]=="admin_promotion") return;
		

		$session = Mage::getSingleton('customer/session');
        $urlHelper = Mage::helper('core/url');
		if($template == 'default' && !$session->isLoggedIn() && !in_array($fullname, $allow))
		{
			if(Mage::app()->getStore()->isAdmin()) return;
			$action->getResponse()->setRedirect(Mage::getUrl('customer/account/landing', array('referer'=>$urlHelper->getEncodedUrl())));
		}

		if($template == 'default' && !isset($_COOKIE['logged_in']) && !in_array($fullname, $allow))
		{
			if(Mage::getSingleton('customer/session')->isLoggedIn())
			{
				return;
			}
			$action->getResponse()->setRedirect(Mage::getUrl('customer/account/landing', array('referer'=>$urlHelper->getEncodedUrl())));
		}

		if(count($names)>0 && $names[0]=="cms") return;
	}

	// 订单生成成功时增加出入库记录
	public function orderPlace($observer)
	{
		$order = $observer->getOrder();

		if($order && $order->getId())
		{
			$items = $order->getAllItems();
			$resource = Mage::getSingleton('core/resource');
			$db = $resource->getConnection('core_read');

			foreach($items as $item) {

				$websiteId = Mage::getModel('core/store')->load($item->getStoreId())->getWebsiteId();
				$comment = '';
		    	$date = $item->getCreatedAt();
		    	
				//$db->beginTransaction();
				$qtyOrdered = (0-$item->getQtyOrdered());
				$sql = "insert into aitoc_inventory_stock(website_id,product_id,qty,operation,order_id,created_at,admin_id,comment) 
				values('{$websiteId}','{$item->getProductId()}','{$qtyOrdered}','2','{$order->getIncrementId()}','{$date}','0','')";
				//echo $sql;
				$db->exec($sql);
				// $sql = "select sum(qty) from aitoc_inventory_stock where product_id='{$item->getProductId()}' and website_id='{$websiteId}' and canceled=0";
				// $query = $db->query($sql);
				// $totalQty = $query->fetchColumn();
				// $sql = "update aitoc_cataloginventory_stock_item set qty='{$totalQty}' where product_id='{$item->getProductId()}' and website_id='{$websiteId}' and stock_id=1";
				// $db->exec($sql);
				//$db->commit();

				if ($item->getExchange()) {
					$activity = Mage::getModel('pms/exchange')->load($item->getActivityId());
					if ($activity && $activity->getId()) {
                        $exProduct = Mage::getModel('pms/exchangeproduct')
							->getCollection()
							->addFieldToFilter('activity_id', array('eq' => $activity->getId()))
                            ->addFieldToFilter('product_id', array('eq' => $item->getProductId()))
							->getFirstItem();
						if ($exProduct && $exProduct->getId()) {
							$qty = $exProduct->getExchangedQty() + $item->getQtyOrdered();
							$exProduct->setExchangedQty($qty);
							$exProduct->save();
						}
					}
				}

				Mage::log("item Id:".$item->getGiftId());
				if ($item->getGiftId()) {
					$gift = Mage::getModel('pms/gift')->load($item->getGiftId());
					if ($gift && $gift->getId()) {
						Mage::log("Gift Id:".$gift->getId());
						$qty = $gift->getUsedQty() + $item->getQtyOrdered();
						$gift->setUsedQty($qty);
						$gift->save();
					}
				}
			}
		}
	}
		
	// 订单取消时取消出库记录
	public function orderCancel($observer)
	{
		Mage::log("Cacel Order");
		$order = $observer->getOrder();
		if($order && $order->getId())
		{
			$items = $order->getAllItems();
			$resource = Mage::getSingleton('core/resource');
			$db = $resource->getConnection('core_read');
			foreach($items as $item)
			{
				$websiteId = Mage::getModel('core/store')->load($item->getStoreId())->getWebsiteId();
				$comment = '';
		    	$date = $item->getCreatedAt();

				//$db->beginTransaction();
				//$qtyOrdered = (0-$item->getQtyOrdered());
				//订单取消时取消出库记录
				//$sql = "insert into aitoc_inventory_stock(website_id,product_id,qty,operation,order_id,created_at,admin_id,comment) 
				//values('{$websiteId}','{$item->getProductId()}','{$qtyOrdered}','2','{$order->getIncrementId()}','{$date}','0','')";
				//echo $sql;
				$sql = "update aitoc_inventory_stock set canceled=1 where product_id='{$item->getProductId()}' and order_id='{$order->getIncrementId()}'";
				$db->exec($sql);
				// $sql = "select sum(qty) from aitoc_inventory_stock where product_id='{$item->getProductId()}' and website_id='{$websiteId}' and canceled=0";
				// $query = $db->query($sql);
				// $totalQty = $query->fetchColumn();
				// $sql = "update aitoc_cataloginventory_stock_item set qty='{$totalQty}' where product_id='{$item->getProductId()}' and website_id='{$websiteId}' and stock_id=1";
		    	// $db->exec($sql);
		    	//$db->commit();
				//return qty after gift order canceled
				if($item->getGiftId())
				{
					$gift = Mage::getModel('pms/gift')->load($item->getGiftId());
					$gift->setUsedQty($gift->getUsedQty()-$item->getQtyOrdered());
					$gift->save();
				}

				//return qty after exchange order canceled
				if($item->getExchange())
				{
					$products = Mage::getModel("pms/exchangeproduct")->getCollection()
						->addFieldToFilter('product_id',array('eq'=>$item->getProductId()))
						->addFieldToFilter('activity_id', array('eq'=>$item->getActivityId()));
					if($products)
					{
						$product = $products->getFirstItem();
						if($product)
						{
							$product->setExchangedQty($product->getExchangedQty()-$item->getQtyOrdered());
							$product->save();
						}
					}


				}
			}
		}
	}
}